'''
Created on 5 Nov 2014

@author: User
'''
import numpy as np;
from main.data.yahoo_api import YahooAPI;
import main.data.static_files as static;
from main.data.my_enums import Country;
from main.data import yahoo_api
from main.lib import tech_ind
from main.data import lead_ind

def sentdexRSI(prices,n=14):
    deltas = np.diff(prices);
    seed= deltas[:n+1];
    up = seed[seed>=0].sum()/n;
    down = -seed[seed<0].sum()/n;
    rs = up/down;
    rsi = np.zeros_like(prices);
    rsi[:n] = 100. - 100./(1+rs);
    
    for i in range(n,len(prices)):
        delta = deltas[i-1];
        if delta >0:
            upval = delta;
            downval=0;
        else:
            upval=0;
            downval = -delta;
        up = (up*(n-1)+upval)/n;
        down = (down*(n-1)+downval)/n;
        rs = up/down;
        rsi[i] = 100. -100./(1.+rs);
        
    return rsi;

def relative_strength(prices, n=14):
    """
    compute the n period relative strength indicator
    http://stockcharts.com/school/doku.php?id=chart_school:glossary_r#relativestrengthindex
    http://www.investopedia.com/terms/r/rsi.asp
    """

    deltas = np.diff(prices)
    seed = deltas[:n+1]
    up = seed[seed>=0].sum()/n
    down = -seed[seed<0].sum()/n
    rs = up/down
    rsi = np.zeros_like(prices)
    rsi[:n] = 100. - 100./(1.+rs)

    for i in range(n, len(prices[::-1])):
        delta = deltas[i-1] # cause the diff is 1 shorter

        if delta>0:
            upval = delta
            downval = 0.
        else:
            upval = 0.
            downval = -delta

        up = (up*(n-1) + upval)/n
        down = (down*(n-1) + downval)/n

        rs = up/down
        rsi[i] = 100. - 100./(1.+rs)

    return rsi
def average_gains(all_data):
    """Average Gain = Sum(Gains +14 Periods / 14)"""
    sum_periods = float(sum(all_data['Close']))
    gains_list = []
    diff = all_data['Close'] - all_data['Open']
    for item in diff:
        if float(item) > 0:
            gains_list.append(float(item))
    return float("{0:.2f}".format((sum(gains_list) + sum_periods) / 14))
 
 
def average_losses(all_data):
    sum_periods = float(sum(all_data['Close']))
    losses_list = []
    diff = all_data['Close'] - all_data['Open']
    for item in diff:
        if item < 0:
            losses_list.append(item)
    return float("{0:.2f}".format((sum(losses_list) + sum_periods) / 14))

def rsi3(closes):
    rs = float("{0:.2f}".format(average_gains(closes) / average_losses(closes)))
    rsi = float("{0:.2f}".format(100 - (100 / (1 + rs))))
    return rsi;

def main():
    #YahooAPI().downloadHistorical(code="msft",ys=2014,ms=10,ds=31,tf="d");
    #name = static.getNameByCode("bp", Country.UK);
    
    prices = yahoo_api.YahooAPI().downloadHistorical("hsba.l", ys=2014,ms=10,ds=8);
    '''
    for close in prices.closes:
        print("Close: " + str(close));
    '''
    
    rsi14 = sentdexRSI(prices.closes)
    #print prices.closes;
    
    
        
    print "Length: " + str(len(rsi14));
    print "Length: " + str(len(prices.closes));
    
    for i in range(len(rsi14)):
        print "{0}: Close Price: {1} RSI14: {2}".format(prices.datestring[i],prices.closes[i],rsi14[i])
    
main();